// 普通HTTP请求实现
const commoneUrl = process.env.VUE_APP_BASE_URL;
const platform = process.env.PLATFORM

/**
 * 基础HTTP请求函数
 * @param {string} url - 请求URL
 * @param {object} data - 请求数据
 * @param {string} method - 请求方法
 * @returns {Promise} 请求结果Promise
 */
const request = (url, data = {}, method = 'POST') => {
  const token = encodeURIComponent(uni.getStorageSync('token') || '')
  const clubId = uni.getStorageSync("club_id") || 0
  const longitude = uni.getStorageSync("longitude") || 0
  const latitude = uni.getStorageSync("latitude") || 0
  const header = {
    'Content-Type': 'application/json',
    'ba-user-token': token,
    'clubid': clubId,
    'platform': platform,
    'latitude': latitude,
    'longitude': longitude
  }
  if (url.substring(0, 4) !== 'http') {
    if (url.substring(0, 1) === '/') {
      url = url.substring(1)
    }
    url = commoneUrl + url
  }
  var promise = new Promise((resolve, reject) => {
    uni.request({
      url: url,
      data: data,
      method: method,
      header: header,
      success: function (res) {
        if (res.statusCode === 200) {
          if (res.data.code == 1 || res.data.code == 200) {
            resolve(res.data);
          } else {
            reject(res.data)
          }
        } else {
          reject(res.data)
        }
      },
      error: function (e) {
        reject('网络出错');
      }
    });
  });
  return promise;
}

/**
 * POST请求
 * @param {string} url - 请求URL
 * @param {object} data - 请求数据
 * @returns {Promise} 请求结果Promise
 */
function postRequest(url, data) {
  return request(url, data, 'POST');
}

/**
 * GET请求
 * @param {string} url - 请求URL
 * @param {object} data - 请求数据
 * @returns {Promise} 请求结果Promise
 */
function getRequest(url, data) {
  return request(url, data, 'GET');
}

module.exports = {
  request,
  post: postRequest,
  get: getRequest
};